package com.hzit.sb2.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hzit.sb2.bean.User;
import com.hzit.sb2.bean.UserItem;
import com.hzit.sb2.bean.weixinEntity.MsgReqBodyEntity;
import com.hzit.sb2.bean.weixinEntity.TxtEntity;
import com.hzit.sb2.mapper.UserMapper;
import com.hzit.sb2.redis.RedisUtil;
import com.hzit.sb2.service.IUserService;
import com.hzit.sb2.util.MyConst;
import com.hzit.sb2.util.weixin.GetUserInfoUtil;
import com.hzit.sb2.util.weixin.MessageUtil;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.util.JAXBSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserSeviceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    GetUserInfoUtil getUserInfoUtil;
    @Autowired
    MessageUtil messageUtil;
    @Autowired
    RedisUtil redisUtil;
    @Override
    public User selectByName(String name, String pwd) {
        return userMapper.selectByName(name,pwd);
    }

    @Override
    public Map<String, Object> getUserListInfo() {
        HashMap<String, Object> hashMap = new HashMap<>();
        Map<String, Object> userOpenId = getUserInfoUtil.getUserOpenId(null);
        hashMap.put("total",userOpenId.get("total"));
        hashMap.put("count",userOpenId.get("count"));
        Map<String, List<UserItem>> userInfoMap = getUserInfoUtil.userInfoList(null, null);
        hashMap.put("userList",userInfoMap.get("user_info_list"));
        return hashMap;
    }

    @Override
    public String qrcode() {
        Object object =  redisUtil.get(MyConst.WEIXIN_QRCODE_KEY);
        if(object == null){
            String qrCode = getUserInfoUtil.getQrCode();
            redisUtil.set(MyConst.WEIXIN_QRCODE_KEY,qrCode);
            return qrCode;
        }
        return (String) object;
    }

    @Override
    public Boolean sendMsg(MsgReqBodyEntity msg, TxtEntity txt) {
        Map<String, Object> map = new HashMap<>();
        map.put("touser",msg.getTouser());
        map.put("msgtype",msg.getMsgtype());
        HashMap<String, String> textMap = new HashMap<>();
        textMap.put("content",txt.getContent());
        map.put("text",textMap);
        String rbody = JSONObject.toJSONString(map);
        String s = messageUtil.sendTxtMsg(rbody);
        System.out.println(s);
        JSONObject object = JSONObject.parseObject(s);
        return true;
    }

    @Override
    public Map<String, Object> findById(String openid) {
        Map<String, Object> map = getUserInfoUtil.userInfo(openid, null);
        return map;
    }
}
